﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pTools.ChildWin;
using pTools.cMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace pTools
{
    public partial class InitPrint : DevExpress.XtraEditors.XtraForm
    {
        cMethods.DBHelper db;
        HttpAgreement http;
        public InitPrint()
        {
            InitializeComponent();
            db = new DBHelper();
            http = new HttpAgreement();
        }

        private void InitPrint_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "期初数据打印";
                loadPrint();
                loadWareHouse();

                loadUnit();
                tb_1_printNum.Text = "1";
                CommonMethods.loadPrintTemplte(cb_0_Template);
                CommonMethods.loadPrintDevice(cb_0_Print);

                // 加载班组 机台
                LoadProduceGroup();

                LoadMachine();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 加载生产班组
        private void LoadProduceGroup()
        {
            var sql = "select ccode,cname from fun_CommonData_Info where cType = 'PROGROUP' and cCode <> ''";
            var dt = db.getData(sql, "");

            cb_1_cu_workGroup.DataSource = dt;
            cb_1_cu_workGroup.DisplayMember = "cname";
            cb_1_cu_workGroup.ValueMember = "ccode";
        }

        private void LoadMachine()
        {
            var sql = "select ccode,cname from fun_CommonData_Info where cType = 'PM' and cCode <> ''";
            var dt = db.getData(sql, "");

            cb_1_machine.DataSource = dt;
            cb_1_machine.DisplayMember = "cname";
            cb_1_machine.ValueMember = "ccode";
        }

        /// <summary>
        /// 打印机列表
        /// </summary>
        private void loadPrint()
        {
            PrintDocument print = new PrintDocument();
            string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
            {
                DataRow r = dt.NewRow();
                r["name"] = sPrint;
                r["value"] = sPrint;
                dt.Rows.Add(r);
            }
            cb_0_Print.DataSource = dt;
            cb_0_Print.ValueMember = "name";
            cb_0_Print.DisplayMember = "name";
            cb_0_Print.SelectedValue = sDefault;
        }
        /// <summary>
        /// 计量单位
        /// </summary>
        private void loadUnit()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select code,name from sys_dictionaries_info where status=1");
            sb.Append(" and  types='prt'");
            var table = db.getData(sb.ToString(), "");
            cb_1_unit.DataSource = table;
            cb_1_unit.ValueMember = "code";
            cb_1_unit.DisplayMember = "name";
        }
        /// <summary>
        /// 仓库信息显示
        /// </summary>
        private void loadWareHouse()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select houseCode,(houseName+'-'+houseCode) houseName from fun_WareHouse_Info where isdel=0 ");
            sb.Append("and status='open' ");
            var table = db.getData(sb.ToString(), "");
            cb_1_wareHouse.DataSource = table;
            cb_1_wareHouse.ValueMember = "houseCode";
            cb_1_wareHouse.DisplayMember = "houseName";
        }

        private void tbProCode_Click(object sender, EventArgs e)
        {
            try
            {
                SelectProduct win = new SelectProduct();
                win.StartPosition = FormStartPosition.CenterScreen;
                win.WindowState = FormWindowState.Normal;

                var result = win.ShowDialog();

                if (result == DialogResult.Cancel)
                {

                }

                if (CommonMethods.Parameters != null)
                {
                    tb_1_ProCode.Text = CommonMethods.Parameters["proCode"];
                    tb_0_ProName.Text = CommonMethods.Parameters["proName"];
                    tb_0_ProName.ReadOnly = true;
                    tb_1_ProCode.ReadOnly = true;

                    tb_0_Spec.Text = CommonMethods.Parameters["spec"];
                    tb_0_Spec.ReadOnly = true;
                }

                //CheckIfFreeOn();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {

                //if (string.IsNullOrEmpty(tb_0_plCode.Text))
                //{
                //    MessageBox.Show("请填写生产计划编码，再点击打印");
                //}

                var datas = CommonMethods.GetFormData(this.gcBar.Controls, null);
                datas["isInitial"] = "Y";
                datas["createuser"] = CommonMethods.userCode;
                var msg = http.PostJson("SaveInitBarCode", JsonConvert.SerializeObject(datas));
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(msg);
                    if (bool.Parse(json["Result"].ToString()))
                    {
                        if (string.IsNullOrWhiteSpace(json["Data"].ToString()))
                        {
                            MessageBox.Show("接口返回数据异常，请联系开发人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        #region 打印代码
                        var bars = json["Data"].ToString();
                        var table = CommonMethods.createPrintTable(this.gcBar.Controls, null, bars);

                        string info = "";
                        var pResult = CommonMethods.DoPrint(table, cb_0_Template.Text, cb_0_Print.Text, ref info);
                        if (!pResult)
                        {
                            MessageBox.Show(msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        // DoneProduct();
                        #endregion
                    }

                    else
                    {
                        MessageBox.Show(json["Message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void VisitService()
        {
            Dictionary<string, string> datas = new Dictionary<string, string>();
            datas["machine"] = "";
            datas["proCode"] = tb_1_ProCode.Text;
            datas["proName"] = tb_0_ProName.Text;
            datas["printNum"] = "1";
            datas["gxCode"] = "-";//期初数据默认标识
            datas["isInitial"] = "Y";
            datas["barStatus"] = "need-in";
            datas["wareHouse"] = cb_1_wareHouse.SelectedValue.ToString();

            datas["warePosition"] = "-";

            datas["planCode"] = "-";
            datas["createuser"] = CommonMethods.userCode;
            datas["barType"] = "QC";
            datas["unit"] = cb_1_unit.SelectedValue.ToString();

            datas["cu_outCompany"] = CommonMethods.singleValue;
            datas["width"] = "-";

            datas["c_gongjin"] = tb_1_number.Text;

            datas["memo"] = "期初数据";

            datas["printNum"] = tb_1_printNum.Text;

            var msg = http.PostJson("SaveBarCode", JsonConvert.SerializeObject(datas));
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var json = JsonConvert.DeserializeObject<JObject>(msg);
                if (bool.Parse(json["Result"].ToString()))
                {
                    if (string.IsNullOrWhiteSpace(json["Data"].ToString()))
                    {
                        MessageBox.Show("接口返回数据异常，请联系开发人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    #region 打印代码
                    var bars = json["Data"].ToString().Split(',');
                    var table = CommonMethods.QcPrintTable();
                    foreach (string s in bars)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            var r = table.NewRow();
                            r["barCode"] = s;
                            r["customName"] = CommonMethods.singleText;
                            r["proName"] = tb_0_ProName.Text;
                            r["gongjin"] = tb_1_number.Text;

                            r["spec"] = tb_0_Spec.Text;
                            r["wareHouse"] = cb_1_wareHouse.Text;
                            r["wPosition"] = "-";
                            r["date"] = DateTime.Now.ToString("yyyy-MM-dd");
                            r["userName"] = CommonMethods.userName;



                            table.Rows.Add(r);
                        }

                    }
                    string info = "";
                    var pResult = CommonMethods.DoPrint(table, cb_0_Template.Text, cb_0_Print.Text, ref info);
                    if (!pResult)
                    {
                        MessageBox.Show(msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    #endregion

                }
                else
                {
                    MessageBox.Show(json["Message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("接口反馈异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void tbCustomer_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 加载通用数据(型号、系列等)
        /// </summary>
        /// <param name="parentCode"></param>
        /// <param name="cbControl"></param>
        private void loadCommonData(string parentCode, string cType, ComboBox cbControl)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select cCode,(cName+'-'+cCode) cName from fun_CommonData_Info where isdel=0 ");
            sb.Append("and status='Y' and parentCode='" + parentCode + "' and specFile='" + CommonMethods.baseCode + "'");
            sb.Append(" and cType='" + cType + "'");
            var table = db.getData(sb.ToString(), "");
            cbControl.DataSource = table;
            cbControl.ValueMember = "cCode";
            cbControl.DisplayMember = "cName";
        }
    }
}
